package cn.itcast.controller;

import cn.itcast.pojo.Dept;
import cn.itcast.pojo.Result;
import cn.itcast.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/depts")
@Slf4j
//跨域
@CrossOrigin
public class DeptController {
    @Autowired
    private DeptService deptService;


    @GetMapping
    public Result findAll(){
        List<Dept> list = deptService.findAll();
        //list.clear();检测返回的Result是否正确报错
        return list.size() == 0? Result.erro("查询失败") : Result.success(list);
    }
    /**
     * 删除部门
     * @param id
     * @return
     */
    @DeleteMapping
    public Result deleteById(int id){
      boolean result = deptService.deleteById(id);

      return result ? Result.success("删除成功") : Result.erro("删除失败");
    }
    /**
     * 添加部门
     * @param dept
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Dept dept){
        boolean result = deptService.add(dept);

        return result ? Result.success("添加成功") : Result.erro("添加失败");
    }


    /**
     * 根据id查询部门
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable int id){
        Dept result = deptService.findById(id);
        return  result == null ?  Result.erro("查找失败"):Result.success(result);
    }

    /**
     * 修改部门
     * @param dept
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Dept dept){
        boolean depts = deptService.update(dept);
        return depts? Result.success("修改成功") : Result.erro("修改失败");
    }
}
